import CTextAreaForm from '@/components/CTextAreaForm/CTextAreaForm'
import IDeptVO from '@/model/vo/dept/IDeptVO'
import useEffectDeptPage from '@/useEffect/useEffectDeptPage'
import { flatTree, listToTree } from '@/util/CommonUtil'
import { Col, Form, useFormState } from '@douyinfe/semi-ui'
import { TreeNodeData } from '@douyinfe/semi-ui/lib/es/tree'
import { useEffect, useState } from 'react'

// 获取 下拉选的数据
export function getAreaFormSelectData(modalVisible: boolean) {
  const { deptList } = useEffectDeptPage(modalVisible)
  return { deptList }
}

interface IAreaFormItem {
  deptList: TreeNodeData[]
  areaTree: IDeptVO[]
}

export default function AreaFormItem(props: IAreaFormItem) {
  const formState = useFormState()
  const [treeData, setTreeData] = useState<TreeNodeData[]>() // 上级菜单（树结构）

  useEffect(() => {
    if (props.areaTree) {
      // 先扁平化树结构
      const areaList = flatTree(
        props.areaTree,
        true,
        (item) => item.id !== formState.values.id // 不要本节点
      ).map((item) => ({
        id: item.id,
        key: item.id,
        value: item.id,
        label: item.name,
        parentId: item.parentId,
      })) as TreeNodeData[]

      // 再 listToTree
      setTreeData(listToTree(areaList))
    }
  }, [props.areaTree])

  return (
    <>
      <Col span={24}>
        <Form.TreeSelect
          field="parentId"
          showClear
          label="上级区域"
          filterTreeNode
          showFilteredOnly
          treeData={treeData}
          className="w100"
          virtualize={{
            height: 300,
            itemSize: 28,
          }}
        ></Form.TreeSelect>
      </Col>
      <Col span={24}>
        <Form.Input
          field="name"
          rules={[{ required: true, message: '请输入区域名称' }]}
          showClear
          label="区域名称"
        />
      </Col>
      <Col span={24}>
        <Form.TreeSelect
          field="deptIdSet"
          showClear
          label="绑定部门"
          filterTreeNode
          showFilteredOnly
          treeData={props.deptList}
          className="w100"
          multiple
          maxTagCount={10}
          checkRelation="unRelated"
          virtualize={{
            height: 300,
            itemSize: 28,
          }}
        ></Form.TreeSelect>
      </Col>
      <Col span={24}>
        <Form.InputNumber
          showClear
          className="w100"
          field="orderNo"
          label="排序号"
        />
      </Col>
      <Col span={24}>
        <Form.Switch field="enableFlag" label="启用" />
      </Col>
      <Col span={24}>
        <CTextAreaForm></CTextAreaForm>
      </Col>
    </>
  )
}
